
package org.sopt.dev.ImgKnight.agent.Executor;

import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.log4j.Logger;

import org.sopt.dev.ImgKnight.agent.Agent;
import org.sopt.dev.ImgKnight.agent.database.HarvestDAO;
import org.sopt.dev.ImgKnight.agent.database.HarvestVO;

public class TakeResourceCompletionHandler implements Runnable {

	private Agent agent = null;

	private HarvestDAO dao = null;
	
	private Logger exceptionLogger = null;
	
	public TakeResourceCompletionHandler() {
		this.agent = Agent.getInstance();
		dao = new HarvestDAO();
		exceptionLogger = Logger.getLogger("agent.exception");
	}
	
	@Override
	public void run() {
		CompletionService<List<HarvestVO>> takeImagecompletionService = 
			agent.getTakeResourceCompletionService();
		while( true ) {
			try {
				Future<List<HarvestVO>> future = takeImagecompletionService.take();
				if( future == null )
					continue;	
				List<HarvestVO> downloaded = future.get();
				if( downloaded != null ) {
					if( downloaded.size() > 0 ) {
						if( dao.insertHarvest(downloaded) )
							agent.onDownloaded(downloaded);
						else
							agent.onMissedDownload(downloaded.size());
					}
					downloaded.clear();
				}
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				return;
			} catch (ExecutionException e) {
				exceptionLogger.warn("ExecutionException: "+e.toString());
			}
		}
	}
	
}
